package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGeneratorUtil;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional // 事务注解(同时操作多张表)
    public void apply(CheckInApplyDto dto) {
        //1.判断老人是否已经入住（存在则抛出异常）
        //通过身份证号查询老人
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        //获取到老人的身份证号码
        elderQueryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());
        //状态（0：禁用，1：启用 2：请假 3：退住中 4入住中 5已退住）
        //查询状态为0,1,2,3,4的老人
        elderQueryWrapper.in(Elder::getStatus,0,1,2,3,4);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if(ObjectUtil.isNotEmpty(elder)){ //老人对象不为空，说明老人已经入住，抛出异常
            throw new RuntimeException("该老人已经入住");
            //或用 throw new BaseException("该老人已经入住");
        }
        //2.更新床位状态为已经入住(直接更新)
        //先获取到床位对象，再更新为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        //床位状态：未入住0，已入住1
        //更新为已入住
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或更新老人数据
        elder = insertOrUpdate(bed, dto.getCheckInElderDto());
        //生成合同编号(生成一个编号，编号长度为16位，其中前12位是当前时间（年月日时分秒），
        // 后四位是从1开始累加的值，第小值为：0001  最大的值为：9999)
        String contractNo = "HT"+CodeGeneratorUtil.generateCode();

        //4.新增签约办理
        insertContract(contractNo, elder,dto);

        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);

        //6.新增入住配置
        insertCheckInConfig(checkIn.getId(), dto);
    }
    /**
     * 查询入住详情
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //入住详情信息
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1.设置入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        //属性拷贝
        BeanUtils.copyProperties(checkIn,checkInConfigVo);

        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //2.设置老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //获取老人ID
        Long elderId = checkIn.getElderId();
        Elder  elder  = elderMapper.selectById(elderId);
        BeanUtils.copyProperties(elder,checkInElderVo);
        //从身份证中获取老人的年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //3.设置家属相应信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        //4.设置签约办理相应信息
        LambdaQueryWrapper<Contract> ContractqueryWrapper = new LambdaQueryWrapper<>();
        ContractqueryWrapper.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(ContractqueryWrapper);
        checkInDetailVo.setContract(contract);

        //返回结果
        return checkInDetailVo;
    }

    /**
     * 新增入住配置
     * @param dto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        //对象属性拷贝
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param dto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        //将老人信息拷贝到入住信息中
        CheckIn checkIn = new CheckIn();
        //封装前端没有传递过来的数据
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        //备注：家属对象列表json字符串
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        //插入入住信息
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增合同
     * @param contractNo
     * @param elder
     * @param dto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        //属性拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人的方法
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //准备老人数据
        Elder elder = new Elder();
        //属性拷贝
        BeanUtils.copyProperties(checkInElderDto,elder); //将前端传递过来的老人数据赋值给elder对象
        //补全前端没有传递过来的信息
        //床位编号
        elder.setBedNumber(bed.getBedNumber());
        //床位ID
        elder.setBedId(bed.getId());
        //状态为（1）入住中
        elder.setStatus(1);
        //查询老人信息（身份证号、状态为5已退住）
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).eq(Elder::getStatus, 5);
        //查询到则更新，否则新增
        Elder elderDb = elderMapper.selectOne(lambdaQueryWrapper);
        if(ObjectUtil.isNotEmpty(elderDb)){ //有值
            //更新
            elderMapper.updateById(elder);
        }else{
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }
}
